"""
# Author : YuuSoo
# version : python 3.8
# Time : 2023/1/7 11:46
"""
# -*- coding: utf-8 -*-
# =============================================================================
# import....
import logging
from datetime import datetime, date

from flask import request, current_app
import flask_restful
from flask_restful import Resource, reqparse
import numpy as np
import pandas as pd
import time
import utils
import json

# 自定义模块
from errors import my_abort, generate_response, ResponseCode

# 自定义错误
flask_restful.abort = my_abort
root_logger = logging.getLogger('root')
logger = logging.getLogger('main')
# =============================================================================

# =============================================================================
# 模型import
# from Src.commissioning_process_recommendation import function
from .get_debug_metrics import function

# =============================================================================


class TJ_commissioning_process_recommendation(Resource):
    def __init__(self):
        self.parser = reqparse.RequestParser(bundle_errors=True)
        # Authorization, fileId1, fileId2, fileName
        self.parser.add_argument('Authorization', type=str, required=True, help="token失效")
        self.parser.add_argument('id', type=str, required=True, help="文件id错误")
        # self.parser.add_argument('fileId2', type=str, required=True, help="需要数据文件绝对路径")
        # self.parser.add_argument('fileName', type=str, required=True, help="fileName error")

    # def get(self):
    #     currentTimeStr = utils.nowTimeText4China()
    #     print('=== 工艺参数推荐开始, 中国时间: %s' % currentTimeStr)
    #
    #     computeDurationStart = time.time()
    #     httpStatusCode = 200
    #     queryParams = self.parser.parse_args()
    #     # 获取参数，根据参数需求增删
    #
    #     logger.info(
    #         '=== 工艺参数推荐请求 ==> GET ')
    #     res = function()
    #
    #     if res['resp_code'] == ResponseCode.WRONG_PARAM:
    #         httpStatusCode = 400
    #     computeDuration = time.time() - computeDurationStart
    #     logger.info('=== 工艺参数推荐 ==> 耗时( %.3f 秒 )' % computeDuration)
    #     return res, httpStatusCode, {"Content-Type": "application/json; charset=utf-8"}

    def post(self):
        currentTimeStr = utils.nowTimeText4China()
        print('=== 工期预测开始, 中国时间: %s' % currentTimeStr)

        computeDurationStart = time.time()
        httpStatusCode = 200
        queryParams = self.parser.parse_args()
        # 获取参数，根据参数需求增删
        # Authorization, fileId1, fileId2, fileName
        Authorization = queryParams.get('Authorization')
        id = queryParams.get('id')
        # fileId2 = queryParams.get('fileId2')
        # fileName = queryParams.get('fileName')
        # savePath2 = queryParams.get('savePath')
        # object_name = queryParams.get('object_name')
        # start = queryParams.get('start')
        # end = queryParams.get('end')

        logger.info('=== 工期预测请求 ==> GET ?\nAuthorization=%s\nid=%s' % (Authorization, id))
        res = function(Authorization, id)

        if res['resp_code'] == ResponseCode.WRONG_PARAM:
            httpStatusCode = 400
        computeDuration = time.time() - computeDurationStart
        logger.info('=== 工期预测 ==> 耗时( %.3f 秒 )' % computeDuration)
        return res, httpStatusCode, {"Content-Type": "application/json; charset=utf-8"}


class NpEncoder(json.JSONEncoder):  # 继承json.JSONEncoder
    def default(self, obj):
        if isinstance(obj, np.integer):
            return int(obj)
        elif isinstance(obj, np.floating):
            return float(obj)
        elif isinstance(obj, np.float):
            return float(obj)
        elif isinstance(obj, np.ndarray):
            return obj.tolist()
        elif isinstance(obj, pd.Timestamp):
            return obj.strftime('%Y-%m-%d %H:%M:%S')
        elif isinstance(obj, datetime):
            return obj.strftime('%Y-%m-%d %H:%M:%S')
        elif isinstance(obj, date):
            return obj.strftime('%Y-%m-%d')
        elif isinstance(obj, np.datetime64):
            return np.datetime_as_string(obj)
        else:
            return super(NpEncoder, self).default(obj)
